package com.bw.home.model.service

import androidx.lifecycle.viewModelScope
import com.bw.common.utils.LogUtils
import com.bw.home.common.SimpleTypeExeception
import com.bw.home.intent.SimpleTypeIntent
import com.bw.home.model.api.SimpleTypeApi
import com.bw.home.state.SimpleTypeState
import com.bw.mvicore.model.BaseModel
import com.bw.mvicore.model.IModel
import com.bw.net.RetrofitUtils
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author:created by hahajing
 * 时间：2024/4/26 0026
 * 企鹅号:444511958
 * 描述:
 */
class SimpleTypeModel:BaseModel<SimpleTypeIntent>() {
    private val api:SimpleTypeApi by lazy {
        RetrofitUtils.create(SimpleTypeApi::class.java)
    }
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SimpleTypeIntent.GetSimpleTypeIntent->{
                        getSimpleType()
                    }
                }
            }
        }
    }

    private val _state:MutableStateFlow<SimpleTypeState> = MutableStateFlow(SimpleTypeState.SimpleTypeDefaultState)
    val state:MutableStateFlow<SimpleTypeState>
        get() = _state

    private fun getSimpleType() {
        viewModelScope.launch {
            val types = api.getSimpleType()
            if (types.code==0){
                LogUtils.d("SimpleTypeModel","do success")
                _state.value = SimpleTypeState.GetSimpleTypeSuceessState(types.data)
            }else{
                _state.value = SimpleTypeState.GetSimpleTypeFailedState(SimpleTypeExeception("获取Simple信息出错，error:${types.msg}"))
            }
        }
    }
}